{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# torch中的神经网络是可以任意定义的，继承Module类并实现forward函数即可轻松定义块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 完成一个块的定义\n",
    "class myblock(torch.nn.Module):\n",
    "    def __init__(self, *args, **kwargs) -> None:\n",
    "        super().__init__(*args, **kwargs)\n",
    "\n",
    "        self.layer1 = torch.nn.Linear(3,5)\n",
    "        self.weight = torch.ones(size=(5,5),requires_grad=False)*2\n",
    "        self.layer2 = torch.nn.Linear(5,2)\n",
    "\n",
    "    def forward(self,x):\n",
    "        x = self.layer1(x)\n",
    "        x = torch.nn.functional.relu(x @ self.weight)\n",
    "        x = torch.nn.functional.relu(self.layer2(x))\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "net = torch.nn.Sequential(myblock(),\n",
    "                          torch.nn.Linear(2,1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.4884], grad_fn=<ViewBackward0>)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.tensor([1,2,3],dtype=torch.float32)\n",
    "Y = net(X)\n",
    "Y"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
